// 全局状态管理
window.state = {
  panelInstance: null,
  runtime: chrome.runtime || browser.runtime,
  autoDownload: false,
  isInitialized: false,
  currentTemplate: null,
  currentDomain: null  // 添加当前域名到状态管理
};

const downloadQueue = [];

// 面板HTML模板
window.panelHTML = `
  <div class="drag-handle">Lofter图片爬虫</div>
  <button class="minimize-btn">_</button>
  <div class="panel-content">
    <div class="control-panel">
      <div id="templateStatus" class="template-status"></div>
      <div class="input-rows">
        <div class="input-field">
          <label>目标图片数：</label>
          <input type="number" id="targetImages" value="5000">
        </div>
        <div class="page-range">
          <label>页码范围：</label>
          <input type="number" id="startPage" value="1">
          <span>-</span>
          <input type="number" id="endPage" value="50">
        </div>
        <div class="input-field">
          <label>子目录文件夹：</label>
          <input type="text" id="subFolder" value="images_xhh">
        </div>
      </div>
      <div id="currentTemplate" class="current-template">
        <div class="template-header">
          <h4>当前页面模板</h4>
          <button id="switchTemplate" class="switch-template-btn">切换模板</button>
        </div>
        <div id="templateInfo"></div>
      </div>
    </div>
    <div class="button-group">
      <button id="startCrawl">开始爬取</button>
      <button id="stopCrawl">结束爬取</button>
      <button id="viewImages">图片浏览</button>
      <button id="downloadImages">图片下载</button>
      <button id="crawlAndDownload">爬取并下载</button>
      <button id="exportExcel">导出Excel</button>
      <button id="resetAll" style="background-color: #f44336;">重置数据</button>
    </div>
    <div class="status-info">
      <p id="articleStatus">已爬取网页：0 个</p>
      <p id="imageStatus">已爬取图片：0 张</p>
      <p id="currentPage">当前页码：0</p>
      <div id="timeStats" class="time-stats">
        <p>总耗时：0 分钟</p>
        <p>平均每张图片耗时：0 毫秒</p>
      </div>
    </div>
  </div>
  <!-- 模板列表对话框 -->
  <div id="templateListDialog" class="dialog">
    <div class="dialog-content">
      <h3>选择模板</h3>
      <div id="templateList"></div>
      <div class="dialog-buttons">
        <button id="addTemplate">添加模板</button>
        <button id="closeTemplateList">关闭</button>
      </div>
    </div>
  </div>
  <!-- 编辑模板对话框 -->
  <div id="editTemplateDialog" class="dialog">
    <div class="dialog-content">
      <h3>编辑模板</h3>
      <div class="form-group">
        <label>域名：</label>
        <input type="text" id="templateDomain" placeholder="例如: lofter.com">
      </div>
      <div class="form-group">
        <label>页面URL模板：</label>
        <input type="text" id="templatePageUrl" placeholder="支持 {current_url} 和 {page} 占位符">
        <div class="input-help">
          {current_url}: 当前页面URL
          {page}: 页码
        </div>
      </div>
      <div class="form-group">
        <label>列表选择器：</label>
        <input type="text" id="templateListSelector" placeholder="例如: .post-list a（可选）">
      </div>
      <div class="form-group">
        <label>图片选择器：</label>
        <input type="text" id="templateImageSelector" placeholder="例如: .post-content img">
      </div>
      <div class="form-group">
        <label>文件名前缀：</label>
        <input type="text" id="templateFilenamePrefix" placeholder="例如: lofter_">
      </div>
      <div class="form-group">
        <label>属性处理器：</label>
        <textarea id="templateAttrHandler" rows="8" placeholder='{"attr": "data-src"}'></textarea>
      </div>
      <div class="dialog-buttons">
        <button id="saveTemplate">保存</button>
        <button id="cancelTemplate">取消</button>
      </div>
    </div>
  </div>
  <!-- 图片查看器对话框 -->
  <div id="imageViewerDialog" class="dialog">
    <div class="dialog-content large">
      <div class="dialog-header">
        <h3>图片浏览</h3>
        <button class="close-dialog">×</button>
      </div>
      <div class="image-grid"></div>
      <div class="viewer-controls-container">
        <div class="viewer-controls">
          <div class="selection-controls">
            <button id="selectCurrentPage">本页全选</button>
            <button id="invertCurrentPage">本页反选</button>
            <button id="selectAll">全选</button>
            <button id="invertAll">反选</button>
          </div>
          <div class="pagination-container">
            <div class="pagination"></div>
            <div class="page-info">1/1页</div>
          </div>
          <div class="download-controls">
            <button id="downloadSelected">选中下载(0/0)</button>
          </div>
        </div>
      </div>
    </div>
  </div>
`;

// 下载配置
window.downloadConfig = {
  batchSize: 10,        // 每批下载的图片数量
  maxConcurrent: 5,     // 最大并发数
  retryCount: 3,        // 重试次数
  retryDelay: 100,      // 重试延迟(ms)
  batchDelay: 50        // 批次间延迟(ms)
};

// 配置管理对象
window.configManager = {
  // 下载配置
  async download() {
    try {
      const response = await fetch(chrome.runtime.getURL('config.json'));
      const config = await response.json();
      return config;
    } catch (error) {
      console.error('下载配置失败:', error);
      throw error;
    }
  },

  // 加载配置
  async load() {
    try {
      // 先尝试从storage获取
      const result = await chrome.storage.local.get('config');
      if (result.config) {
        return result.config;
      }

      // 如果storage中没有，则下载默认配置
      const config = await this.download();
      // 保存到storage
      await this.save(config);
      return config;
    } catch (error) {
      console.error('加载配置失败:', error);
      throw error;
    }
  },

  // 保存配置
  async save(config) {
    try {
      await chrome.storage.local.set({ config });
      return true;
    } catch (error) {
      console.error('保存配置失败:', error);
      throw error;
    }
  }
};

// 定义全局按钮处理函数
window.buttons = {
  'startCrawl': async () => {
    try {
      // 禁用其他按钮
      document.querySelectorAll('.button-group button').forEach(btn => {
        if (btn.id !== 'startCrawl' && btn.id !== 'stopCrawl') {
          btn.disabled = true;
        }
      });
      
      // 获取当前选择器
      const currentTemplate = state.currentTemplate;
      
      if (!currentTemplate || !currentTemplate.selectors) {
        throw new Error('无法加载配置或配置无效');
      }
      const targetImages = document.getElementById('targetImages')?.value || 5000;
      const startPage = document.getElementById('startPage')?.value || 1;
      const endPage = document.getElementById('endPage')?.value || 50;
      await crawlImages(currentTemplate, [], parseInt(targetImages), parseInt(startPage), parseInt(endPage));
    } catch (error) {
      console.error('开始爬取失败:', error);
      toast.show(error.message, 'error');
    } finally {
      // 恢复其他按钮
      document.querySelectorAll('.button-group button').forEach(btn => {
        btn.disabled = false;
      });
    }
  },
  'stopCrawl': () => {
    state.isCrawling = false;
  },
  'viewImages': async () => {
    if (!window.imageViewer) {
      window.imageViewer = new ImageViewer();
    }
    window.imageViewer.show();
  },
  'downloadImages': async () => {
    try {
      const result = await chrome.storage.local.get('images');
      const images = result.images || [];
      if (images.length === 0) {
        toast.show('没有可下载的图片', 'warning');
        return;
      }
      await batchDownloadImages(images);
    } catch (error) {
      console.error('下载图片失败:', error);
      toast.show('下载失败，请重试', 'error');
    }
  },
  'exportExcel': exportToCSV,
  'crawlAndDownload': async () => {
    try {
      // 禁用其他按钮
      document.querySelectorAll('.button-group button').forEach(btn => {
        if (btn.id !== 'crawlAndDownload' && btn.id !== 'stopCrawl') {
          btn.disabled = true;
        }
      });
      
      console.log('开始爬取并下载');
      // 设置自动下载标志
      state.autoDownload = true;
      
      // 确保使用当前选中的模板
      if (!state.currentTemplate) {
        throw new Error('请先选择或设置模板');
      }
      
      const config = {
        selectors: state.currentTemplate.selectors
      };
      
      if (!config || !config.selectors) {
        throw new Error('无法加载配置或配置无效');
      }
      
      console.log('使用的模板配置:', config);
      
      // 重置计数器
      await chrome.storage.local.set({ images: [], articles: [] });
      // 更新显示
      updateStatus();
      // 开始爬取
      const targetImages = document.getElementById('targetImages')?.value || 5000;
      const startPage = document.getElementById('startPage')?.value || 1;
      const endPage = document.getElementById('endPage')?.value || 50;
      
      // 爬取图片
      const images = await crawlImages(config, [], parseInt(targetImages), parseInt(startPage), parseInt(endPage));
      
      // 如果爬取成功且有图片，开始下载
      if (images && images.length > 0) {
        console.log('开始下载爬取到的图片');
        await batchDownloadImages(images);
      } else {
        console.log('没有找到可下载的图片');
        toast.show('没有找到可下载的图片', 'warning');
      }
      
    } catch (error) {
      console.error('爬取并下载失败:', error);
      toast.show('爬取并下载失败: ' + error.message, 'error');
    } finally {
      // 恢复其他按钮
      document.querySelectorAll('.button-group button').forEach(btn => {
        btn.disabled = false;
      });
      // 重置自动下载标志
      state.autoDownload = false;
    }
  },
  'resetAll': async () => {
    if (confirm('确定要清除所有已爬取的数据吗？')) {
      await chrome.storage.local.remove(['images', 'articles']);
      document.getElementById('articleStatus').textContent = '已爬取网页：0 个';
      document.getElementById('imageStatus').textContent = '已爬取图片：0 张';
      document.getElementById('currentPage').textContent = '当前页码：0';
    }
  },
  'manageTemplates': () => {
    console.log('点击管理模板按钮');
    const templateDialog = document.getElementById('templateDialog');
    console.log('模板对话框元素:', templateDialog);
    if (templateDialog) {
      console.log('开始加载模板');
      loadTemplates().then(() => {
        console.log('模板加载完成，显示对话框');
        templateDialog.style.display = 'flex';
      });
    }
  },
  'closeDialog': () => {
    const templateDialog = document.getElementById('templateDialog');
    if (templateDialog) {
      templateDialog.style.display = 'none';
    }
  },
  'addTemplate': async () => {
    try {
      const domain = window.location.hostname;
      const detectedSelectors = await detectSelectors();
      
      // 填充表单
      document.getElementById('templateDomain').value = domain;
      document.getElementById('templatePageUrl').value = window.location.href;
      document.getElementById('templateListSelector').value = detectedSelectors?.listSelector || '';
      document.getElementById('templateImageSelector').value = detectedSelectors?.imageSelector || '';
      
      // 显示编辑对话框
      document.getElementById('editTemplateDialog').style.display = 'flex';
    } catch (error) {
      console.error('添加模板失败:', error);
      toast.show('添加模板失败: ' + error.message, 'error');
    }
  },
  'cancelTemplate': () => {
    const editDialog = document.getElementById('editTemplateDialog');
    if (editDialog) {
      editDialog.style.display = 'none';
    }
  },
  'saveTemplate': async () => {
    try {
      const domain = document.getElementById('templateDomain').value;
      if (!domain) {
        toast.show('域名不能为空！', 'warning');
        return;
      }

      // 解析属性处理器JSON
      let attrHandler = null;
      const attrHandlerText = document.getElementById('templateAttrHandler').value;
      if (attrHandlerText) {
        try {
          attrHandler = JSON.parse(attrHandlerText);
        } catch (error) {
          toast.show('属性处理器JSON格式无效！', 'error');
          return;
        }
      }

      const template = {
        pageUrl: document.getElementById('templatePageUrl').value,
        listSelector: document.getElementById('templateListSelector').value,
        imageSelector: document.getElementById('templateImageSelector').value,
        filename_prefix: document.getElementById('templateFilenamePrefix').value,
        attrHandler: attrHandler
      };

      // 获取配置
      const config = await configManager.load();
      if (!config || !config.selectors) {
        throw new Error('配置数据无效');
      }

      // 保存到配置
      config.selectors[domain] = template;
      await configManager.save(config);

      // 更新当前模板
      if (domain === state.currentDomain) {
        state.currentTemplate = template;
        updateTemplateStatus();
      }

      // 更新模板列表
      showTemplateList();
      
      // 保持选中状态
      const templateItem = document.querySelector(`[data-domain="${domain}"]`);
      if (templateItem) {
        templateItem.classList.add('selected');
      }

      document.getElementById('editTemplateDialog').style.display = 'none';
      toast.show('模板保存成功', 'success');
    } catch (error) {
      console.error('保存模板失败:', error);
      toast.show('保存失败：' + error.message, 'error');
    }
  }
};

// 调试信息
console.log('Content script 加载开始');
console.log('Chrome runtime:', chrome);
console.log('Browser runtime:', typeof browser !== 'undefined' ? browser : 'undefined');

// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', async () => {
  console.log('DOM加载完成，初始化消息监听器');
  initializeMessageListener();
});

// 初始化消息监听器
window.initializeMessageListener = function() {
  try {
    // 检查runtime是否可用
    if (!state.runtime) {
      console.error('Chrome runtime 不可用');
      return;
    }
    
    console.log('设置消息监听器');
    if (!state.isInitialized) {
      state.runtime.onMessage.addListener(window.handleMessage);
      state.isInitialized = true;
    }
    console.log('消息监听器设置成功');
  } catch (error) {
    console.error('初始化消息监听器失败:', error);
  }
}

// 消息处理函数
window.handleMessage = function(request, sender, sendResponse) {
  console.log('收到消息:', request);
  
  try {
    if (request.type === 'startCrawl') {
      // 获取目标数量
      const targetImages = document.getElementById('targetImages')?.value || 5000;
      const targetPages = document.getElementById('targetPages')?.value || 50;

      crawlImages(
        request.config,
        request.existingArticles || [],
        parseInt(targetImages),
        parseInt(targetPages)
      );
      sendResponse({ success: true });
    } else if (request.action === 'togglePanel') {
      handleTogglePanel();
      sendResponse({ success: true });
    } else if (request.type === 'newArticle') {
      handleNewArticle(request.url);
      sendResponse({ success: true });
    } else if (request.type === 'updateCurrentPage') {
      handlePageUpdate(request.page);
      sendResponse({ success: true });
    }
  } catch (error) {
    console.error('处理消息出错:', error);
    sendResponse({ success: false, error: error.message });
  }
  
  return true;
}

// 处理面板切换
window.handleTogglePanel = async function() {
  try {
    if (!state.panelInstance) {
      // 创建面板
      const panel = document.createElement('div');
      panel.id = 'lofterCrawlerPanel';
      panel.innerHTML = window.panelHTML;
      document.body.appendChild(panel);
      state.panelInstance = panel;
      
      // 等待DOM更新
      await new Promise(resolve => setTimeout(resolve, 0));
      
      // 初始化面板功能
      initializePanelFunctions(panel);
    } else {
      // 切换面板显示状态
      state.panelInstance.style.display = state.panelInstance.style.display === 'none' ? 'block' : 'none';
    }
  } catch (error) {
    console.error('处理面板切换失败:', error);
    window.toast.show('面板初始化失败: ' + error.message, 'error');
  }
}

// 初始化面板功能
window.initializePanelFunctions = function(panel) {
  try {
    // 检查当前页面的模板匹配
    checkCurrentPageTemplate();
    
    // 添加最小化功能
    const minimizeBtn = panel.querySelector('.minimize-btn');
    if (minimizeBtn) {
      minimizeBtn.addEventListener('click', () => {
        panel.classList.toggle('minimized');
        minimizeBtn.textContent = panel.classList.contains('minimized') ? '□' : '_';
      });
    }
    
    // 添加模板切换按钮事件
    const switchTemplateBtn = panel.querySelector('#switchTemplate');
    const templateListDialog = panel.querySelector('#templateListDialog');
    const closeTemplateListBtn = panel.querySelector('#closeTemplateList');
    const addTemplateBtn = panel.querySelector('#addTemplate');
    
    if (switchTemplateBtn) {
      switchTemplateBtn.addEventListener('click', () => {
        templateListDialog.style.display = 'flex';
        window.loadTemplates(true); // true表示是切换模式
      });
    }
    
    if (closeTemplateListBtn) {
      closeTemplateListBtn.addEventListener('click', () => {
        templateListDialog.style.display = 'none';
      });
    }
    
    if (addTemplateBtn) {
      addTemplateBtn.addEventListener('click', () => {
        // 隐藏模板列表对话框
        templateListDialog.style.display = 'none';
        // 显示编辑模板对话框，传入空值表示新建
        window.editTemplate('', {
          pageUrl: '',
          listSelector: '',
          imageSelector: ''
        });
      });
    }
    
    // 添加模板编辑对话框的按钮事件
    const saveTemplateBtn = panel.querySelector('#saveTemplate');
    const cancelTemplateBtn = panel.querySelector('#cancelTemplate');
    
    if (saveTemplateBtn) {
      saveTemplateBtn.addEventListener('click', async () => {
        await window.buttons.saveTemplate();
      });
    }
    
    if (cancelTemplateBtn) {
      cancelTemplateBtn.addEventListener('click', () => {
        document.getElementById('editTemplateDialog').style.display = 'none';
      });
    }
    
    // 绑定按钮事件
    document.querySelectorAll('.button-group button').forEach(button => {
      const action = button.id;
      if (window.buttons[action]) {
        button.addEventListener('click', window.buttons[action]);
      }
    });
    
    // 在面板创建完成后初始化子目录文件夹
    setTimeout(() => {
      initializeSubFolder();
    }, 100);
  } catch (error) {
    console.error('初始化面板功能失败:', error);
    window.toast.show('初始化面板功能失败: ' + error.message, 'error');
  }
}

// 检查脚本是否已加载
function isScriptLoaded(src) {
  return document.querySelector(`script[src="${src}"]`) !== null;
}

// 加载脚本
async function loadScript(src) {
  if (isScriptLoaded(src)) {
    console.log('脚本已加载:', src);
    return;
  }
  
  return new Promise((resolve, reject) => {
    const script = document.createElement('script');
    script.src = state.runtime.getURL(src);
    script.type = 'text/javascript';
    script.onload = resolve;
    script.onerror = reject;
    document.head.appendChild(script);
  });
}

// 通过background脚本获取页面内容
async function fetchWithBackground(url) {
  try {
    console.log('请求页面:', url);
    return new Promise((resolve, reject) => {
      // 创建一个隐藏的iframe来加载动态页面
      const iframe = document.createElement('iframe');
      iframe.style.display = 'none';
      document.body.appendChild(iframe);
      
      // 设置超时处理
      const timeout = setTimeout(() => {
        cleanup();
        reject(new Error('加载页面超时'));
      }, 30000); // 30秒超时
      
      // 清理函数
      const cleanup = () => {
        clearTimeout(timeout);
        if (iframe) {
          document.body.removeChild(iframe);
        }
      };
      
      // 监听iframe加载完成
      iframe.onload = () => {
        try {
          // 等待一段时间让动态内容加载完成
          setTimeout(() => {
            try {
              // 获取iframe中的内容
              const doc = iframe.contentDocument || iframe.contentWindow.document;
              const html = doc.documentElement.outerHTML;
              cleanup();
              resolve({ data: html });
            } catch (error) {
              cleanup();
              reject(new Error('无法访问iframe内容，可能是跨域限制'));
            }
          }, 2000); // 等待2秒让动态内容加载
        } catch (error) {
          cleanup();
          reject(error);
        }
      };
      
      // 监听错误
      iframe.onerror = (error) => {
        cleanup();
        reject(new Error('iframe加载失败: ' + error.message));
      };
      
      // 加载URL
      iframe.src = url;
    });
  } catch (error) {
    console.error('获取页面失败:', error);
    throw error;
  }
}

// 验证URL是否为图片
function isImageUrl(url) {
  try {
    const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
    const urlLower = url.toLowerCase();
    return imageExtensions.some(ext => urlLower.endsWith(ext));
  } catch (error) {
    console.error('验证图片URL失败:', error);
    return false;
  }
}

// 下载单张图片
async function downloadImage(url, index) {
  try {
    // 获取子目录名称
    const subFolder = document.getElementById('subFolder')?.value || 'images';
    
    // 从URL中提取文件扩展名
    const extension = url.split('.').pop().split(/[#?]/)[0].toLowerCase() || 'jpg';
    
    // 构建文件名
    const filename = `${subFolder}/image_${Date.now()}.${extension}`;
    
    // 通用请求头
    const headers = {
      'Referer': window.location.href,
      'User-Agent': navigator.userAgent,
      'Accept': 'image/webp,image/apng,image/*,*/*;q=0.8',
      'Accept-Language': 'en-US,en;q=0.9',
      'Cache-Control': 'no-cache'
    };

    // 记录下载状态
    const downloadStatus = JSON.parse(localStorage.getItem('downloadStatus') || '{}');
    
    try {
      // 首先尝试使用chrome.downloads API
      const response = await chrome.runtime.sendMessage({
        type: 'downloadImage',
        url: url,
        filename: filename,
        headers: headers
      });

      if (response && response.success) {
        downloadStatus[url] = '成功';
        console.log(`图片下载成功(chrome.downloads): ${filename}`);
        localStorage.setItem('downloadStatus', JSON.stringify(downloadStatus));
        return response;
      }
    } catch (error) {
      console.warn('chrome.downloads下载失败，尝试使用fetch:', error);
    }

    // 如果chrome.downloads失败，使用fetch
    try {
      const response = await fetch(url, { 
        headers,
        mode: 'no-cors',  // 添加no-cors模式
        credentials: 'omit'  // 不发送cookies
      });

      if (response.ok) {
        const blob = await response.blob();
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = filename;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(link.href);
        
        downloadStatus[url] = '成功';
        console.log(`图片下载成功(fetch): ${filename}`);
        localStorage.setItem('downloadStatus', JSON.stringify(downloadStatus));
        return { success: true };
      } else {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
    } catch (error) {
      console.error('fetch下载失败:', error);
      // 最后尝试使用background script下载
      try {
        const response = await chrome.runtime.sendMessage({
          type: 'fetchUrl',
          url: url,
          options: {
            mode: 'no-cors',
            credentials: 'omit',
            headers: headers
          }
        });
        
        if (response && response.success) {
          const blob = await response.data.blob();
          const link = document.createElement('a');
          link.href = URL.createObjectURL(blob);
          link.download = filename;
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          URL.revokeObjectURL(link.href);
          
          downloadStatus[url] = '成功';
          console.log(`图片下载成功(background): ${filename}`);
          localStorage.setItem('downloadStatus', JSON.stringify(downloadStatus));
          return { success: true };
        }
      } catch (bgError) {
        console.error('background下载失败:', bgError);
        downloadStatus[url] = '失败';
        localStorage.setItem('downloadStatus', JSON.stringify(downloadStatus));
        throw bgError;
      }
      downloadStatus[url] = '失败';
      localStorage.setItem('downloadStatus', JSON.stringify(downloadStatus));
      throw error;
    }
  } catch (error) {
    console.error('下载图片失败:', error);
    throw error;
  }
}

// 批量下载图片
async function downloadSelectedImages(selectedImages) {
  try {
    if (!selectedImages || selectedImages.length === 0) {
      toast.show('没有可下载的图片', 'warning');
      return;
    }

    console.log(`开始下载 ${selectedImages.length} 张图片`);
    const statusDiv = document.getElementById('downloadStatus') || createDownloadStatus();

    for (let i = 0; i < selectedImages.length; i++) {
      try {
        await downloadImage(selectedImages[i], i + 1);
        statusDiv.textContent = `下载进度: ${i + 1}/${selectedImages.length}`;
      } catch (error) {
        console.error(`下载第 ${i + 1} 张图片失败:`, error);
        continue;
      }

      await new Promise(resolve => setTimeout(resolve, 100));
    }

    toast.show('图片下载完成', 'success');
  } catch (error) {
    console.error('批量下载失败:', error);
    toast.show('下载失败: ' + error.message, 'error');
  }
}

// 创建下载状态显示
function createDownloadStatus() {
  const statusDiv = document.createElement('div');
  statusDiv.id = 'downloadStatus';
  statusDiv.className = 'download-status';
  const statusInfo = document.querySelector('.status-info');
  if (statusInfo) {
    statusInfo.appendChild(statusDiv);
  }
  return statusDiv;
}

// 发送图片URL到background
async function sendImageUrl(url) {
  try {
    console.log('处理图片URL:', url);
    // 从storage获取现有图片列表
    const result = await chrome.storage.local.get('images');
    console.log('从storage获取的图片列表:', result);
    const images = new Set(result.images || []);
    console.log('当前图片集合大小:', images.size);
    
    // 添加新图片
    if (!images.has(url)) {
      console.log('添加新图片到列表:', url);
      images.add(url);
      console.log('添加后图片集合大小:', images.size);
      const imageArray = Array.from(images);
      console.log('准备保存到storage的图片数组:', imageArray);
      await chrome.storage.local.set({ images: imageArray });
      console.log('图片列表已保存到storage');
      
      // 更新状态显示
      console.log('开始更新状态显示');
      updateStatus();
      
      // 如果是自动下载模式，直接下载图片
      if (state.autoDownload) {
        console.log('自动下载模式，开始下载:', url);
        const filename = `lofter_images/${Date.now()}_${url.split('/').pop()}`;
        await downloadSingleImage(url, filename);
      }
      
      // 检查是否达到目标数量
      const targetImages = document.getElementById('targetImages')?.value || 5000;
      console.log('目标图片数量:', targetImages, '当前数量:', images.size);
      if (images.size >= parseInt(targetImages)) {
        console.log('达到目标图片数量，停止爬取');
        stopCrawling();
      }
    } else {
      console.log('图片已存在，跳过:', url);
    }
  } catch (error) {
    console.error('处理图片URL失败:', error);
    console.error('错误详情:', error.message);
    console.error('错误堆栈:', error.stack);
  }
}

// 爬虫主函数
async function crawlImages(config, existingImages = [], targetCount = 5000, startPage = 1, endPage = 50) {
  try {
    state.isCrawling = true;
    const crawledImages = [...existingImages];
    
    // 获取初始图片
    const images = document.querySelectorAll(config.selectors.imageSelector);
    console.log(`初始找到 ${images.length} 张图片`);
    
    // 处理初始图片
    for (const img of images) {
      if (!state.isCrawling || crawledImages.length >= targetCount) break;
      
      let imageUrl = null;
      if (config.selectors.attrHandler) {
        imageUrl = getImageUrl(img, window.location.hostname, config.selectors.attrHandler);
      } else {
        imageUrl = img.src;
      }
      
      if (imageUrl && !crawledImages.includes(imageUrl)) {
        crawledImages.push(imageUrl);
        updateImageCount(crawledImages.length);
      }
    }
    
    // 如果还没达到目标数量，开始滚动加载
    if (state.isCrawling && crawledImages.length < targetCount) {
      await autoScroll(config, crawledImages, targetCount);
    }

    return crawledImages;
  } catch (error) {
    console.error('爬取图片失败:', error);
    throw error;
  }
}

// 处理新文章
async function handleNewArticle(url) {
  try {
    // 从storage获取现有文章列表
    const result = await chrome.storage.local.get('articles');
    const articles = new Set(result.articles || []);
    
    // 添加新文章
    articles.add(url);
    
    // 保存更新后的文章列表
    await chrome.storage.local.set({ articles: Array.from(articles) });
    
    // 更新状态显示
    updateStatus();
  } catch (error) {
    console.error('处理新文章失败:', error);
  }
}

// 处理页面更新
function handlePageUpdate(page) {
  try {
    const pageElement = document.getElementById('currentPage');
    if (pageElement) {
      pageElement.textContent = `当前页码：${page}`;
    }
    
    // 检查是否达到目标页数
    const targetPages = document.getElementById('targetPages')?.value || 50;
    if (page >= parseInt(targetPages)) {
      stopCrawling();
    }
  } catch (error) {
    console.error('处理页面更新失败:', error);
  }
}

// 更新状态显示
window.updateStatus = function(currentPage = 0, imageCount = 0) {
  try {
    const statusInfo = document.querySelector('.status-info');
    const articleStatus = document.getElementById('articleStatus');
    const imageStatus = document.getElementById('imageStatus');
    const currentPageStatus = document.getElementById('currentPage');
    
    // 获取已处理的文章数
    chrome.storage.local.get('articles', (result) => {
      const articles = result.articles || [];
      if (articleStatus && articles.length > 0) {
        articleStatus.textContent = `已爬取网页：${articles.length} 个`;
      }
    });
    
    // 更新图片数量
    if (imageStatus && imageCount > 0) {
      imageStatus.textContent = `已爬取图片：${imageCount} 张`;
    }
    
    // 更新当前页码
    if (currentPageStatus && currentPage > 0) {
      currentPageStatus.textContent = `当前页码：${currentPage}`;
    }
    
    // 检查是否完成
    if (statusInfo) {
      const targetImages = parseInt(document.getElementById('targetImages')?.value || 5000);
      const endPage = parseInt(document.getElementById('endPage')?.value || 50);
      
      if (!state.isCrawling && (
        imageCount >= targetImages || 
        currentPage >= endPage || 
        imageCount === 0
      )) {
        statusInfo.classList.add('completed');
      } else {
        statusInfo.classList.remove('completed');
      }
    }
  } catch (error) {
    console.error('更新状态显示失败:', error);
  }
}

// 停止爬取
function stopCrawling() {
  console.log('停止爬取');
  state.isCrawling = false;
}

// 检查当前页面的模板匹配
window.checkCurrentPageTemplate = async function() {
  try {
    const currentDomain = window.location.hostname;
    console.log('当前页面域名:', currentDomain);

    // 加载配置
    const config = await configManager.load();
    
    // 查找匹配的模板
    const matchedTemplate = Object.entries(config.selectors).find(([domain]) => 
      currentDomain.includes(domain) || domain.includes(currentDomain)
    );

    const templateInfo = document.getElementById('templateInfo');
    if (!templateInfo) return;

    if (matchedTemplate) {
      const [domain, selectors] = matchedTemplate;
      console.log('找到匹配模板:', domain, selectors);
      // 设置初始的当前模板
      state.currentTemplate = {
        domain: domain,
        selectors: selectors
      };
      templateInfo.innerHTML = `
        <p><strong>域名:</strong> ${domain}</p>
        <p><strong>页面URL:</strong> ${selectors.pageUrl || '未设置'}</p>
        <p><strong>列表选择器:</strong> ${selectors.listSelector}</p>
        <p><strong>图片选择器:</strong> ${selectors.imageSelector}</p>
      `;
      templateInfo.classList.remove('no-match');
    } else {
      console.log('未找到匹配模板');
      templateInfo.innerHTML = '当前页面没有匹配的模板';
      templateInfo.classList.add('no-match');
    }
  } catch (error) {
    console.error('检查页面模板失败:', error);
  }
}

// 更新当前模板显示
function updateCurrentTemplate(domain, selectors) {
  const templateInfo = document.getElementById('templateInfo');
  if (!templateInfo) return;
  
  // 保存当前选中的模板到state
  state.currentTemplate = {
    domain: domain,
    selectors: selectors
  };
  
  templateInfo.innerHTML = `
    <p><strong>域名:</strong> ${domain}</p>
    <p><strong>页面URL:</strong> ${selectors.pageUrl || '未设置'}</p>
    <p><strong>列表选择器:</strong> ${selectors.listSelector}</p>
    <p><strong>图片选择器:</strong> ${selectors.imageSelector}</p>
  `;
  templateInfo.classList.remove('no-match');
}

// 加载模板列表
window.loadTemplates = async function(isSwitchMode = false) {
  try {
    console.log('开始加载模板列表');
    const currentDomain = window.location.hostname;
    console.log('当前域名:', currentDomain);
    
    // 从本地文件加载默认配置
    const defaultConfigResponse = await fetch(chrome.runtime.getURL('config.json'));
    const defaultConfig = await defaultConfigResponse.json();
    console.log('默认配置:', defaultConfig);

    // 从storage获取配置
    const result = await chrome.storage.local.get('config');
    console.log('Storage配置:', result);

    // 合并配置
    const config = {
      selectors: {
        ...defaultConfig.selectors,
        ...(result.config?.selectors || {})
      }
    };
    console.log('合并后的配置:', config);

    const templateList = document.getElementById('templateList');
    if (!templateList) {
      console.error('未找到模板列表元素');
      return;
    }
    
    templateList.innerHTML = '';
    
    if (!config.selectors || Object.keys(config.selectors).length === 0) {
      console.log('没有找到模板配置');
      templateList.innerHTML = '<p>暂无模板</p>';
      return;
    }

    let listHtml = '';
    Object.entries(config.selectors).forEach(([domain, selectors]) => {
      listHtml += generateTemplateHTML(domain, selectors);
    });

    templateList.innerHTML = listHtml;
    
    // 查找匹配的模板
    let matchedDomain = null;
    if (state.currentTemplate) {
      // 如果有当前选中的模板，优先使用
      matchedDomain = state.currentTemplate.domain;
    } else {
      // 否则尝试匹配当前域名
      matchedDomain = Object.keys(config.selectors).find(domain => 
        currentDomain.includes(domain) || domain.includes(currentDomain)
      );
    }
    
    console.log('匹配的模板域名:', matchedDomain);

    // 绑定事件和设置选中状态
    templateList.querySelectorAll('.template-item').forEach(item => {
      const domain = item.dataset.domain;
      // 如果是切换模式且找到匹配的模板，选中它
      if (isSwitchMode && domain === matchedDomain) {
        item.classList.add('selected');
        // 更新当前模板显示
        updateCurrentTemplate(domain, config.selectors[domain]);
      }
      
      item.addEventListener('click', (e) => {
        // 如果点击的是按钮，不触发选择
        if (e.target.tagName === 'BUTTON') return;
        
        const domain = item.dataset.domain;
        const selectors = config.selectors[domain];
        
        // 移除其他选中状态
        templateList.querySelectorAll('.template-item').forEach(i => {
          i.classList.remove('selected');
        });
        
        // 添加选中状态
        item.classList.add('selected');
        
        // 更新当前模板显示和状态
        updateCurrentTemplate(domain, selectors);
        
        if (isSwitchMode) {
          // 关闭对话框
          document.getElementById('templateListDialog').style.display = 'none';
        }
      });
    });

    // 绑定按钮事件
    templateList.querySelectorAll('.edit-btn').forEach(btn => {
      const domain = btn.dataset.domain;
      const selectors = config.selectors[domain];
      btn.addEventListener('click', () => {
        console.log('点击编辑按钮:', domain);
        editTemplate(domain, selectors);
      });
    });

    // 绑定复制按钮事件
    templateList.querySelectorAll('.copy-btn').forEach(btn => {
      const domain = btn.dataset.domain;
      const selectors = config.selectors[domain];
      btn.addEventListener('click', () => {
        console.log('点击复制按钮:', domain);
        // 复制模板到新建表单
        copyTemplate(domain, selectors);
      });
    });

    templateList.querySelectorAll('.delete-btn').forEach(btn => {
      const domain = btn.dataset.domain;
      btn.addEventListener('click', () => {
        console.log('点击删除按钮:', domain);
        deleteTemplate(domain);
      });
    });

    console.log('模板列表渲染完成');
  } catch (error) {
    console.error('加载模板列表失败:', error);
    const templateList = document.getElementById('templateList');
    if (templateList) {
      templateList.innerHTML = `<p style="color: red;">加载模板失败: ${error.message}</p>`;
    }
  }
}

// 修改模板列表的HTML生成
function generateTemplateHTML(domain, selectors) {
  return `
    <div class="template-item" data-domain="${domain}">
      <div class="template-info">
        <h4>${domain}</h4>
        <p>页面URL: ${selectors.pageUrl || '未设置'}</p>
        <p>列表选择器: ${selectors.listSelector}</p>
        <p>图片选择器: ${selectors.imageSelector}</p>
      </div>
      <div class="template-actions">
        <button class="edit-btn" data-domain="${domain}">编辑</button>
        <button class="copy-btn" data-domain="${domain}">复制</button>
        <button class="delete-btn" data-domain="${domain}">删除</button>
      </div>
    </div>
  `;
}

// 添加编辑模板函数
window.editTemplate = function(domain, selectors) {
  console.log(domain ? '编辑模板:' : '新建模板:', domain, selectors);
  const editDialog = document.getElementById('editTemplateDialog');
  if (editDialog) {
    document.getElementById('templateDomain').value = domain;
    document.getElementById('templatePageUrl').value = selectors.pageUrl || '';
    document.getElementById('templateListSelector').value = selectors.listSelector || '';
    document.getElementById('templateImageSelector').value = selectors.imageSelector || '';
    document.getElementById('templateFilenamePrefix').value = selectors.filename_prefix || 'lofter_';
    document.getElementById('templateAttrHandler').value = 
      selectors.attrHandler ? JSON.stringify(selectors.attrHandler, null, 2) : '';
    
    editDialog.querySelector('h3').textContent = domain ? '编辑模板' : '新建模板';
    editDialog.style.display = 'flex';
  }
}

// 添加删除模板函数
window.deleteTemplate = async function(domain) {
  console.log('删除模板:', domain);
  if (confirm(`确定要删除 ${domain} 的模板吗？`)) {
    try {
      const config = await configManager.load();
      if (config.selectors && config.selectors[domain]) {
        delete config.selectors[domain];
        await configManager.save(config);
        await loadTemplates(); // 重新加载模板列表
      }
    } catch (error) {
      console.error('删除模板失败:', error);
      toast.show('删除模板失败，请重试！', 'error');
    }
  }
}

// 修改收集图片URL的函数
async function collectImages(doc, selectors) {
  try {
    console.log('\n----------------- 开始收集图片 -----------------');
    const domain = new URL(window.location.href).hostname;
    console.log('使用的选择器:', JSON.stringify(selectors, null, 2));
    

    // 获取当前已收集的图片数量
    const result = await chrome.storage.local.get('images');
    const currentImages = result.images || [];
    
    // 创建下载队列
    let downloadQueue = [];
    
    if (selectors.listSelector) {
      const listItems = doc.querySelectorAll(selectors.listSelector);
      console.log(`[列表] 使用选择器 "${selectors.listSelector}" 找到 ${listItems.length} 个列表项`);
      
      let allImages = [];
      
      for (const item of listItems) {
        // 检查是否需要停止
        if (!state.isCrawling) {
          console.log('收到停止信号，中断爬取');
          break;
        }
        
        // 检查是否达到目标数量, targetImages.value 是目标数量, 转换为数字
        if (currentImages.length + allImages.length >= parseInt(targetImages.value)) {
          console.log('已达到目标图片数量，停止爬取');
          break;
        }
        
        const href = item.href || item.getAttribute('href');
        if (!href) {
          console.log('[跳过] 列表项没有href属性');
          continue;
        }
        
        try {
          console.log(`\n[访问] 文章页面: ${href}`);
          
          // 获取文章页面的HTML
          const response = await fetchWithBackground(href);
          const parser = new DOMParser();
          const doc = parser.parseFromString(response.data, 'text/html');

          // 更新articleStatus
          handleNewArticle(href);

          // 在文章页面中查找图片
          const imageElements = doc.querySelectorAll(selectors.imageSelector);
          console.log(`[图片] 在文章中找到 ${imageElements.length} 个图片元素`);
          
          // 处理每个图片元素

          for (const img of imageElements) {
            // 再次检查是否达到目标数量
            if (currentImages.length + allImages.length >= targetImages) {
              break;
            }
            
            let imageUrl = null;
            if (selectors.attrHandler) {
              imageUrl = getImageUrl(img, domain, selectors.attrHandler);
            } else {
              imageUrl = img.src;
            }
            
            if (imageUrl) {
              allImages.push(imageUrl);

              // 更新已爬取图片数量
              const imageStatus = document.getElementById('imageStatus');
              if (imageStatus) {
                imageStatus.textContent = `已爬取图片: ${currentImages.length + allImages.length}`;
              }

              // 获取子目录文件夹
              const subFolder = document.getElementById('subFolder').value || 'images_xhh';

              // 如果是自动下载模式，添加到下载队列
              if (state.autoDownload) {
                downloadQueue.push(imageUrl);
                // 当队列达到一定大小时处理下载
                if (downloadQueue.length >= 5) {
                  await processDownloadQueue();
                }
              }
            }


          }
          
          console.log(`[进度] 当前已收集 ${allImages.length} 张图片`);
          
          // 如果是自动下载模式，处理下载队列
          if (state.autoDownload && downloadQueue.length > 0) {
            console.log(`开始下载队列中的 ${downloadQueue.length} 张图片`);
            for (const item of downloadQueue) {
              try {
                await new Promise((resolve, reject) => {
                  chrome.runtime.sendMessage(
                    { 
                      type: 'downloadImage',
                      url: item,
                      filename: `${subFolder}/${selectors.filename_prefix}_${currentImages.length + allImages.length}${getImageExtension(item)}`
                    },
                    response => {
                      if (response.success) {
                        resolve();
                      } else {
                        reject(new Error(response.error));
                      }
                    }
                  );
                });

                // imageStatus
                const imageStatus = document.getElementById('imageStatus');
                if (imageStatus) {
                  imageStatus.textContent = `已爬取图片: ${currentImages.length + allImages.length}张`;
                }
                
                // 短暂延时避免下载过快
                await new Promise(resolve => setTimeout(resolve, 200));

              } catch (error) {
                console.error('下载失败:', error);
              }
            }
            // 清空下载队列
            downloadQueue = [];
          }
          
          // 添加随机延时，避免频繁请求
          const delay = Math.random() * 1000;
          console.log(`[延时] 等待 ${Math.round(delay/1000)} 秒后继续...`);
          await new Promise(resolve => setTimeout(resolve, delay));
        } catch (error) {
          console.error(`[错误] 处理文章 ${href} 失败:`, error);
          continue;
        }
      }
      
      return allImages;
    } else {
      // 如果没有列表选择器，直接获取当前页面的图片
      const imageElements = document.querySelectorAll(selectors.imageSelector);
      console.log(`[图片] 使用选择器 "${selectors.imageSelector}" 找到 ${imageElements.length} 个图片元素`);

      // 详细记录每个图片元素的处理过程
      const images = Array.from(imageElements).map((img, index) => {
        console.log(`\n[处理] 图片元素 ${index + 1}/${imageElements.length}:`);
        console.log('原始元素:', img.outerHTML);
        
        if (selectors.attrHandler) {
          console.log('属性处理器配置:', JSON.stringify(selectors.attrHandler, null, 2));
          const url = getImageUrl(img, domain, selectors.attrHandler);
          console.log('最终URL:', url || '(无效)');
          return url;
        } else {
          console.log('使用默认src属性');
          const url = img.src;
          console.log('图片URL:', url || '(无效)');
          return url;
        }
      }).filter(url => {
        const valid = !!url;
        if (!valid) {
          console.log('[过滤] 移除无效URL');
        }
        return valid;
      });

      console.log('\n----------------- 收集结果 -----------------');
      console.log(`成功获取 ${images.length} 个有效图片URL:`);
      images.forEach((url, index) => console.log(`${index + 1}. ${url}`));
      console.log('--------------------------------------------\n');
      return images;
    }
  } catch (error) {
    console.error('收集图片失败:', error);
    throw error;
  }
}

// 根据配置规则提取图片URL
function getImageUrl(imgElement, domain, selectors) {
  try {
    // 获取配置的属性和处理规则
    const { attr = 'src', urlProcessRules = [] } = selectors;
    
    console.log(`尝试获取属性: ${attr}`);
    // 获取指定属性值
    const attrValue = imgElement.getAttribute(attr) || imgElement[attr];
    console.log('获取到的属性值:', attrValue);
    
    if (!attrValue) {
      console.log('未找到属性值');
      return null;
    }
    
    // 按照配置的规则处理URL
    let processedUrl = attrValue;
    for (const rule of urlProcessRules) {
      console.log('\n应用规则:', rule);
      console.log('处理前URL:', processedUrl);
      
      try {
        switch (rule.type) {
          case 'filter':
            // 使用正则表达式过滤URL
            const filterRegex = new RegExp(rule.pattern, rule.ignoreCase ? 'i' : '');
            // 如果不匹配pattern则过滤掉
            if (!filterRegex.test(processedUrl)) {
              console.log('URL被过滤:', processedUrl);
              return null;
            }
            console.log('URL匹配保留:', processedUrl);
            break;
          case 'regex_extract':
            // 使用正则表达式提取URL
            const regex = new RegExp(rule.pattern, 'i');
            const match = processedUrl.match(regex);
            console.log('正则匹配结果:', match);
            processedUrl = match ? match[rule.groupIndex || 0] : null;
            break;
          case 'prefix_add':
            // 添加前缀
            if (!processedUrl.startsWith('http')) {
              processedUrl = rule.prefix + processedUrl;
            }
            break;
          case 'replace':
            // 字符串替换
            const replaceRegex = new RegExp(rule.from, 'g');
            processedUrl = processedUrl.replace(replaceRegex, rule.to);
            break;
        }
        
        console.log('处理后URL:', processedUrl);
        if (!processedUrl) {
          console.log('规则处理后URL无效');
          return null;
        }
      } catch (ruleError) {
        console.error('处理规则出错:', ruleError);
        continue;
      }
    }

    // 处理相对路径
    if (processedUrl.startsWith('//')) {
      processedUrl = 'https:' + processedUrl;
    } else if (processedUrl.startsWith('/')) {
      processedUrl = `https://${domain}${processedUrl}`;
    }

    console.log('最终URL:', processedUrl);
    return processedUrl;
  } catch (error) {
    console.error('处理图片URL失败:', error);
    return null;
  }
}

// 添加URL处理规则的HTML
function addUrlRuleHTML(rule = {}) {
  const ruleDiv = document.createElement('div');
  ruleDiv.className = 'url-rule';
  ruleDiv.innerHTML = `
    <select class="rule-type">
      <option value="regex_extract" ${rule.type === 'regex_extract' ? 'selected' : ''}>正则提取</option>
      <option value="prefix_add" ${rule.type === 'prefix_add' ? 'selected' : ''}>添加前缀</option>
      <option value="replace" ${rule.type === 'replace' ? 'selected' : ''}>替换</option>
    </select>
    <div class="rule-params">
      ${getRuleParamsHTML(rule)}
    </div>
    <button type="button" class="remove-rule">删除</button>
  `;
  
  // 绑定规则类型变化事件
  ruleDiv.querySelector('.rule-type').addEventListener('change', (e) => {
    const paramsDiv = ruleDiv.querySelector('.rule-params');
    paramsDiv.innerHTML = getRuleParamsHTML({ type: e.target.value });
  });
  
  // 绑定删除按钮事件
  ruleDiv.querySelector('.remove-rule').addEventListener('click', () => {
    ruleDiv.remove();
  });
  
  document.getElementById('urlRules').appendChild(ruleDiv);
}

// 获取规则参数的HTML
function getRuleParamsHTML(rule) {
  switch (rule.type) {
    case 'regex_extract':
      return `
        <input type="text" class="rule-pattern" placeholder="正则表达式" value="${rule.pattern || ''}">
        <input type="number" class="rule-group" placeholder="匹配组索引" value="${rule.groupIndex || 0}">
      `;
    case 'prefix_add':
      return `
        <input type="text" class="rule-prefix" placeholder="URL前缀" value="${rule.prefix || ''}">
      `;
    case 'replace':
      return `
        <input type="text" class="rule-from" placeholder="查找内容" value="${rule.from || ''}">
        <input type="text" class="rule-to" placeholder="替换为" value="${rule.to || ''}">
      `;
    default:
      return '';
  }
}

// 添加复制模板函数
function copyTemplate(domain, selectors) {
  console.log('复制模板:', domain, selectors);
  // 显示编辑对话框
  const editDialog = document.getElementById('editTemplateDialog');
  if (editDialog) {
    // 填充表单，但域名留空
    document.getElementById('templateDomain').value = '';
    document.getElementById('templatePageUrl').value = selectors.pageUrl || '';
    document.getElementById('templateListSelector').value = selectors.listSelector || '';
    document.getElementById('templateImageSelector').value = selectors.imageSelector || '';
    document.getElementById('templateFilenamePrefix').value = selectors.filename_prefix || 'lofter_';
    document.getElementById('templateAttrHandler').value = 
      selectors.attrHandler ? JSON.stringify(selectors.attrHandler, null, 2) : '';
    
    // 设置标题为新建模板
    editDialog.querySelector('h3').textContent = '新建模板';
    editDialog.style.display = 'flex';
  }
}

// 图片查看器类
window.ImageViewer = class {
  constructor() {
    this.pageSize = 21;  // 每页固定21张图片
    this.currentPage = 1;
    this.images = [];
    this.selectedImages = new Set();
    this.dialog = null;
    this.previewModal = null;
  }

  async initialize() {
    // 创建预览模态框
    this.previewModal = document.createElement('div');
    this.previewModal.className = 'image-preview-modal';
    document.body.appendChild(this.previewModal);
    
    // 点击模态框关闭预览
    this.previewModal.addEventListener('click', () => {
      this.previewModal.style.display = 'none';
    });

    // 创建主要内容区域
    const viewerContent = document.createElement('div');
    viewerContent.className = 'viewer-content';
    this.dialog.appendChild(viewerContent);

    // 添加图片网格
    const imageGrid = document.createElement('div');
    imageGrid.className = 'image-grid';
    viewerContent.appendChild(imageGrid);

    // 底部控制栏
    const controls = document.createElement('div');
    controls.className = 'viewer-controls-container';

    // 左侧控制区域
    const controlsLeft = document.createElement('div');
    controlsLeft.className = 'controls-left';

    // 按钮组
    const selectControls = document.createElement('div');
    selectControls.className = 'select-controls';

    // 添加选择按钮
    const selectButtons = [
      { id: 'togglePageSelect', text: '本页全选', activeText: '本页反选' },
      { id: 'toggleAllSelect', text: '全选', activeText: '反选' },
      { id: 'downloadSelected', text: '下载选中', type: 'download' }
    ];

    selectButtons.forEach(btn => {
      const button = document.createElement('button');
      button.id = btn.id;
      button.textContent = btn.text;
      button.className = `viewer-button${btn.type ? ' ' + btn.type : ''}`;
      button.dataset.normalText = btn.text;
      button.dataset.activeText = btn.activeText;
      
      // 绑定按钮事件
      if (btn.id === 'togglePageSelect') {
        button.addEventListener('click', () => {
          this.togglePageSelect();
          button.textContent = this.isPageSelected() ? btn.activeText : btn.text;
        });
      } else if (btn.id === 'toggleAllSelect') {
        button.addEventListener('click', () => {
          this.toggleAllSelect();
          button.textContent = this.isAllSelected() ? btn.activeText : btn.text;
        });
      } else if (btn.id === 'downloadSelected') {
        button.addEventListener('click', () => this.downloadSelected());
      }
      selectControls.appendChild(button);
    });

    // 选中计数
    const counter = document.createElement('span');
    counter.className = 'selection-counter';
    counter.textContent = '0/0';

    selectControls.appendChild(counter);
    controlsLeft.appendChild(selectControls);

    // 右侧分页区域
    const controlsRight = document.createElement('div');
    controlsRight.className = 'controls-right';

    // 分页信息
    const paginationInfo = document.createElement('div');
    paginationInfo.className = 'pagination-info';

    // 分页控件
    const pagination = document.createElement('div');
    pagination.className = 'pagination';

    controlsRight.appendChild(paginationInfo);
    controlsRight.appendChild(pagination);

    controls.appendChild(controlsLeft);
    controls.appendChild(controlsRight);

    this.dialog.appendChild(controls);
  }

  render() {
    const grid = this.dialog.querySelector('.image-grid');
    grid.innerHTML = '';

    const start = (this.currentPage - 1) * this.pageSize;
    const end = Math.min(start + this.pageSize, this.images.length);

    for (let i = start; i < end; i++) {
      const imageUrl = this.images[i];
      const imageItem = document.createElement('div');
      imageItem.className = 'image-item';
      if (this.selectedImages.has(i)) {
        imageItem.classList.add('selected');
      }

      const img = document.createElement('img');
      img.src = imageUrl;
      imageItem.appendChild(img);

      // 单击选中
      imageItem.addEventListener('click', () => this.toggleSelect(i));
      
      // 双击预览
      imageItem.addEventListener('dblclick', () => this.showPreview(imageUrl));

      grid.appendChild(imageItem);
    }

    this.updatePagination();
  }

  showPreview(imageUrl) {
    this.previewModal.innerHTML = `<img src="${imageUrl}">`;
    this.previewModal.style.display = 'flex';
  }

  updatePagination() {
    const totalPages = Math.ceil(this.images.length / this.pageSize);
    const paginationInfo = this.dialog.querySelector('.pagination-info');
    if (paginationInfo) {
      paginationInfo.textContent = `${this.currentPage}/${totalPages}页 共${this.images.length}张图片`;
    }

    const pagination = this.dialog.querySelector('.pagination');
    if (pagination) {
      pagination.innerHTML = '';
      // 添加分页按钮
      const buttons = [
        { text: '首页', page: 1 },
        { text: '上一页', page: this.currentPage - 1 },
        { text: this.currentPage, page: this.currentPage, active: true },
        { text: '下一页', page: this.currentPage + 1 },
        { text: '末页', page: totalPages }
      ];

      buttons.forEach(btn => {
        if (btn.page > 0 && btn.page <= totalPages) {
          const button = document.createElement('button');
          button.textContent = btn.text;
          if (btn.active) button.classList.add('active');
          button.addEventListener('click', () => {
            this.currentPage = btn.page;
            this.render();
          });
          pagination.appendChild(button);
        }
      });
    }
  }

  toggleSelect(index) {
    if (this.selectedImages.has(index)) {
      this.selectedImages.delete(index);
    } else {
      this.selectedImages.add(index);
    }
    this.updateSelectionCount();
    this.render();
  }

  async show() {
    // 如果dialog不存在，创建它
    if (!this.dialog) {
      this.dialog = document.createElement('div');
      this.dialog.id = 'imageViewerDialog';
      document.body.appendChild(this.dialog);
      
      // 添加标题栏
      const header = document.createElement('div');
      header.className = 'dialog-header';
      header.innerHTML = `
        <h3>图片浏览</h3>
        <button class="close-dialog">&times;</button>
      `;
      this.dialog.appendChild(header);
      
      // 绑定关闭按钮事件
      header.querySelector('.close-dialog').addEventListener('click', () => {
        this.dialog.style.display = 'none';
      });
      
      // 初始化界面
      await this.initialize();
    }
    
    // 显示对话框
    this.dialog.style.display = 'flex';
    
    // 加载图片数据
    const result = await chrome.storage.local.get('images');
    this.images = result.images || [];
    
    // 渲染界面
    this.render();
  }
  
  // 切换选中状态
  toggleSelect(index) {
    if (this.selectedImages.has(index)) {
      this.selectedImages.delete(index);
    } else {
      this.selectedImages.add(index);
    }
    this.updateSelectionCount();
    this.render();
  }
  
  // 全选/反选
  toggleSelectAll() {
    const start = (this.currentPage - 1) * this.pageSize;
    const end = Math.min(start + this.pageSize, this.images.length);
    
    // 检查当前页是否全部选中
    let allSelected = true;
    for (let i = start; i < end; i++) {
      if (!this.selectedImages.has(i)) {
        allSelected = false;
        break;
      }
    }
    
    // 如果全部选中则取消选中，否则全选
    for (let i = start; i < end; i++) {
      if (allSelected) {
        this.selectedImages.delete(i);
      } else {
        this.selectedImages.add(i);
      }
    }
    
    this.render();
  }
  
  // 下载选中的图片
  async downloadSelected() {
    const selectedImages = Array.from(this.selectedImages)
      .map(i => this.images[i])
      .filter(url => url);
      
    if (selectedImages.length === 0) {
      toast.show('请先选择要下载的图片', 'warning');
      return;
    }
    
    try {
      await downloadSelectedImages(selectedImages);
      toast.show(`已开始下载${selectedImages.length}张图片`, 'success');
    } catch (error) {
      console.error('下载失败:', error);
      toast.show('下载失败，请重试', 'error');
    }
  }

  // 检查当前页是否全选
  isPageSelected() {
    const start = (this.currentPage - 1) * this.pageSize;
    const end = Math.min(start + this.pageSize, this.images.length);
    for (let i = start; i < end; i++) {
      if (!this.selectedImages.has(i)) return false;
    }
    return true;
  }
  
  // 检查是否全部选中
  isAllSelected() {
    return this.selectedImages.size === this.images.length;
  }
  
  // 切换当前页选择状态
  togglePageSelect() {
    const start = (this.currentPage - 1) * this.pageSize;
    const end = Math.min(start + this.pageSize, this.images.length);
    const isAllSelected = this.isPageSelected();
    
    for (let i = start; i < end; i++) {
      if (isAllSelected) {
        this.selectedImages.delete(i);
      } else {
        this.selectedImages.add(i);
      }
    }
    this.updateSelectionCount();
    this.render();
  }
  
  // 切换全部选择状态
  toggleAllSelect() {
    const isAllSelected = this.isAllSelected();
    if (isAllSelected) {
      this.selectedImages.clear();
    } else {
      for (let i = 0; i < this.images.length; i++) {
        this.selectedImages.add(i);
      }
    }
    this.updateSelectionCount();
    this.render();
  }
  
  // 更新选中计数
  updateSelectionCount() {
    const counter = this.dialog.querySelector('.selection-counter');
    if (counter) {
      counter.textContent = `${this.selectedImages.size}/${this.images.length}`;
    }
  }
}

// 导出为CSV
async function exportToCSV() {
  try {
    // 获取图片列表
    const result = await chrome.storage.local.get('images');
    const images = result.images || [];
    
    if (images.length === 0) {
      toast.show('没有可导出的图片', 'warning');
      return;
    }
    
    // 获取下载状态
    const downloadStatus = JSON.parse(localStorage.getItem('downloadStatus') || '{}');
    
    // 准备CSV内容
    const csvContent = [
      ['图片地址', '下载状态'],
      ...images.map(url => [
        url,
        downloadStatus[url] || ''
      ])
    ].map(row => row.map(cell => `"${cell}"`).join(',')).join('\n');
    
    // 创建Blob并下载
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `图片列表_${new Date().toISOString().slice(0,10)}.csv`;
    
    // 触发下载
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(link.href);
    
    toast.show('导出成功', 'success');
  } catch (error) {
    console.error('导出CSV失败:', error);
    toast.show('导出失败: ' + error.message, 'error');
  }
}

// 在initializePanel函数中添加
function initializeSubFolder() {
  const subFolderInput = document.getElementById('subFolder');
  if (!subFolderInput) {
    console.warn('子目录文件夹输入框未找到');
    return;
  }
  
  const urlParams = new URLSearchParams(window.location.search);
  const q = urlParams.get('q');
  
  if (q) {
    subFolderInput.value = q;
  } else {
    subFolderInput.value = 'images_xhh';
  }
  
  console.log('子目录文件夹初始化完成:', subFolderInput.value);
}

// 创建美化的提示框组件
window.Toast = class {
  constructor() {
    this.toast = null;
    this.timeout = null;
  }

  show(message, type = 'info', duration = 3000) {
    // 如果已经存在toast，先移除
    if (this.toast) {
      document.body.removeChild(this.toast);
      clearTimeout(this.timeout);
    }

    // 创建toast元素
    this.toast = document.createElement('div');
    this.toast.className = `toast toast-${type}`;
    this.toast.innerHTML = `
      <div class="toast-content">
        <span class="toast-message">${message}</span>
      </div>
    `;

    // 添加到页面
    document.body.appendChild(this.toast);

    // 添加显示类名触发动画
    setTimeout(() => this.toast.classList.add('show'), 10);

    // 设置定时器自动关闭
    this.timeout = setTimeout(() => {
      this.hide();
    }, duration);
  }

  hide() {
    if (this.toast) {
      this.toast.classList.remove('show');
      setTimeout(() => {
        if (this.toast && this.toast.parentNode) {
          document.body.removeChild(this.toast);
        }
        this.toast = null;
      }, 300);
    }
  }
}

// 创建全局toast实例
window.toast = new window.Toast(); 

// 创建下载队列管理器
class DownloadQueue {
  constructor(concurrency = 3) {
    this.queue = [];
    this.processing = new Set();
    this.concurrency = concurrency;
    this.downloadStats = {
      startTime: 0,
      totalSize: 0,
      downloadedCount: 0
    };
  }

  async add(imageUrl) {
    this.queue.push(imageUrl);
    this.processQueue();
  }

  async processQueue() {
    if (this.processing.size >= this.concurrency || this.queue.length === 0) {
      return;
    }

    const url = this.queue.shift();
    this.processing.add(url);

    try {
      const startTime = Date.now();
      await downloadImage(url);
      const endTime = Date.now();

      this.downloadStats.downloadedCount++;
      const duration = endTime - startTime;
      console.log(`下载耗时: ${duration}ms, 平均速度: ${this.getAverageSpeed()}`);
    } catch (error) {
      console.error('下载失败:', error);
    } finally {
      this.processing.delete(url);
      this.processQueue();
    }
  }

  getAverageSpeed() {
    const totalTime = Date.now() - this.downloadStats.startTime;
    return `${(this.downloadStats.downloadedCount / (totalTime / 1000)).toFixed(2)}张/秒`;
  }
}

// 加载XLSX库
async function loadXLSX() {
  try {
    // 检查XLSX是否已加载
    if (typeof XLSX !== 'undefined') {
      return;
    }
    
    const script = document.createElement('script');
    script.src = chrome.runtime.getURL('lib/xlsx.full.min.js');
    
    await new Promise((resolve, reject) => {
      script.onload = resolve;
      script.onerror = reject;
      document.head.appendChild(script);
    });
    
    // 等待XLSX对象可用
    await new Promise(resolve => setTimeout(resolve, 100));
    
    if (typeof XLSX === 'undefined') {
      throw new Error('XLSX库加载失败');
    }
  } catch (error) {
    console.error('加载XLSX失败:', error);
    throw error;
  }
}

// 导出图片列表
async function exportImageList() {
  try {
    const images = await chrome.storage.local.get('images');
    const imageList = images.images || [];
    
    // 尝试使用XLSX
    try {
      await loadXLSX();
      if (typeof XLSX !== 'undefined') {
        return exportToExcel(imageList);
      }
    } catch (error) {
      console.warn('XLSX不可用，使用CSV格式');
    }
    
    // 使用CSV格式
    return exportToCSV(imageList);
  } catch (error) {
    console.error('导出失败:', error);
    toast.show('导出失败: ' + error.message, 'error');
  }
}

// 提取处理单个页面图片的逻辑为独立函数
async function processPageImages(doc, crawledImages, config, autoDownload) {
  const images = doc.querySelectorAll(config.selectors.imageSelector);
  console.log(`页面找到 ${images.length} 张图片`);
      
  for (const img of images) {
    if (!state.isCrawling || crawledImages.length >= targetCount) break;

    let imageUrl = null;
    if (config.selectors.attrHandler) {
      imageUrl = getImageUrl(img, null, config.selectors.attrHandler);
    } else {
      imageUrl = img.src;
    }
    
    if (imageUrl && !crawledImages.includes(imageUrl)) {
      crawledImages.push(imageUrl);
      
      // 更新图片计数
      const imageCount = document.getElementById('imageStatus');
      if (imageCount) {
        imageCount.textContent = `已爬取图片：${crawledImages.length} 张`;
      }
      
      // 保存到storage
      await chrome.storage.local.set({ images: crawledImages });
      
      // 如果开启了自动下载，添加到下载队列
      if (autoDownload) {
        downloadQueue.push(imageUrl);
        if (downloadQueue.length >= 5) {
          await processDownloadQueue();
        }
      }
    }
  }
}

// 查找真实的滚动容器
function findScrollContainer() {
  // 常见的滚动容器选择器
  const containerSelectors = [
    '.scroll-container', '.infinite-scroll', '.masonry', 
    '.waterfall', '.feed-list', '.timeline',
    '[class*="scroll"]', '[class*="list"]', '[class*="feed"]',
    '[class*="container"]'
  ];

  // 检查所有可能的容器
  for (const selector of containerSelectors) {
    const containers = document.querySelectorAll(selector);
    for (const container of containers) {
      const style = window.getComputedStyle(container);
      // 检查是否有滚动条且内容超出
      if (
        (style.overflow === 'auto' || style.overflow === 'scroll' || 
         style.overflowY === 'auto' || style.overflowY === 'scroll') &&
        container.scrollHeight > container.clientHeight
      ) {
        return container;
      }
    }
  }
  
  // 如果没找到特定容器，返回document.documentElement（整页滚动）
  return document.documentElement;
}

// 改进的滚动加载功能
async function autoScroll(config, crawledImages, targetCount) {
  return new Promise((resolve) => {
    // 找到真实的滚动容器
    const scrollContainer = findScrollContainer();
    console.log('找到滚动容器:', scrollContainer);
    
    let previousImageCount = 0;
    let noUpdateCount = 0;
    const maxNoUpdateCount = 5; // 连续5次没有新图片就停止
    
    const scrollInterval = setInterval(async () => {
      if (!state.isCrawling) {
        clearInterval(scrollInterval);
        resolve();
        return;
      }

      // 执行滚动
      if (scrollContainer === document.documentElement) {
        window.scrollBy(0, 800);
      } else {
        scrollContainer.scrollBy(0, 800);
      }

      // 等待一段时间让新内容加载
      await new Promise(r => setTimeout(r, 1000));

      // 获取当前图片
      const currentImages = document.querySelectorAll(config.selectors.imageSelector);
      console.log(`当前页面图片数量: ${currentImages.length}`);

      // 处理新加载的图片
      for (let i = previousImageCount; i < currentImages.length; i++) {
        if (!state.isCrawling || crawledImages.length >= targetCount) {
          clearInterval(scrollInterval);
          resolve();
          return;
        }

        const img = currentImages[i];
        let imageUrl = null;
        if (config.selectors.attrHandler) {
          imageUrl = getImageUrl(img, window.location.hostname, config.selectors.attrHandler);
        } else {
          imageUrl = img.src;
        }

        if (imageUrl && !crawledImages.includes(imageUrl)) {
          crawledImages.push(imageUrl);
          updateImageCount(crawledImages.length);
          // 保存到storage
          await chrome.storage.local.set({ images: crawledImages });
          // 重置未更新计数
          noUpdateCount = 0;
        }
      }

      // 检查是否有新图片加载
      if (currentImages.length === previousImageCount) {
        noUpdateCount++;
        console.log(`没有新图片加载，计数：${noUpdateCount}/${maxNoUpdateCount}`);
        if (noUpdateCount >= maxNoUpdateCount) {
          console.log('连续多次没有新图片，停止滚动');
          clearInterval(scrollInterval);
          resolve();
          return;
        }
      } else {
        previousImageCount = currentImages.length;
        noUpdateCount = 0;
      }

      // 检查是否到达容器底部
      const isAtBottom = scrollContainer === document.documentElement
        ? (window.innerHeight + window.pageYOffset) >= document.documentElement.scrollHeight - 100
        : scrollContainer.scrollTop + scrollContainer.clientHeight >= scrollContainer.scrollHeight - 100;

      if (isAtBottom) {
        console.log('到达容器底部');
        // 等待更长时间，让可能的加载触发
        await new Promise(r => setTimeout(r, 2000));
        
        // 再次检查是否有新内容
        const newImages = document.querySelectorAll(config.selectors.imageSelector);
        if (newImages.length === previousImageCount) {
          console.log('底部等待后没有新内容，停止滚动');
          clearInterval(scrollInterval);
          resolve();
        }
      }
    }, 1500); // 滚动间隔
  });
}

// 修改爬取函数以使用改进的滚动功能
async function crawlImages(config, existingImages = [], targetCount = 5000) {
  try {
    state.isCrawling = true;
    const crawledImages = [...existingImages];
    
    // 获取初始图片
    const images = document.querySelectorAll(config.selectors.imageSelector);
    console.log(`初始找到 ${images.length} 张图片`);
    
    // 处理初始图片
    for (const img of images) {
      if (!state.isCrawling || crawledImages.length >= targetCount) break;
      
      let imageUrl = null;
      if (config.selectors.attrHandler) {
        imageUrl = getImageUrl(img, window.location.hostname, config.selectors.attrHandler);
      } else {
        imageUrl = img.src;
      }
      
      if (imageUrl && !crawledImages.includes(imageUrl)) {
        crawledImages.push(imageUrl);
        updateImageCount(crawledImages.length);
      }
    }
    
    // 如果还没达到目标数量，开始滚动加载
    if (state.isCrawling && crawledImages.length < targetCount) {
      await autoScroll(config, crawledImages, targetCount);
    }

    return crawledImages;
  } catch (error) {
    console.error('爬取图片失败:', error);
    throw error;
  }
}

// 更新图片计数显示
function updateImageCount(count) {
  const imageStatus = document.getElementById('imageStatus');
  if (imageStatus) {
    imageStatus.textContent = `已爬取图片：${count} 张`;
  }
  
  // 检查是否达到目标数量
  const targetImages = document.getElementById('targetImages')?.value || 5000;
  if (count >= parseInt(targetImages)) {
    console.log('达到目标图片数量，停止爬取');
    state.isCrawling = false;
  }
}